package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.PageInfo;
import com.tanhua.dubbo.server.pojo.PeachSound;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/3/4 18:54
 * @version: 0.0.1
 * @modified By:
 */
@Service(version = "1.0.0")
public class PeachApiImpl implements PeachApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String savePeachSound(PeachSound peachSound) {
        if(null==peachSound.getUserId()){
            return null;
        }
        try {
            peachSound.setId(ObjectId.get());
            peachSound.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(peachSound);
            return peachSound.getId().toHexString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PeachSound queryPeachSoundById(String peachSoundId) {
        PeachSound peachSound = this.mongoTemplate.findById(peachSoundId, PeachSound.class);
        return peachSound;
    }

    @Override
    public PageInfo<PeachSound> queryPeachSoundList(Integer page, Integer pageSize) {
        Pageable pageable= PageRequest.of(page-1,pageSize, Sort.by(Sort.Order.desc("created")));
        Query query=new Query().with(pageable);
        List<PeachSound> peachSounds = this.mongoTemplate.find(query, PeachSound.class);
        PageInfo<PeachSound>pageInfo=new PageInfo<>();
        pageInfo.setTotal(0);
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(peachSounds);
        return pageInfo;
    }
}
